package middleware

import (
	"coze_for_sdk/model"
	"errors"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		Authorization := c.GetHeader("Authorization")
		Bearer := "Bearer "
		token := Authorization[len(Bearer):]

		if Authorization == "" {
			c.AbortWithStatusJSON(200, Result{
				Code:    4001,
				Data:    "",
				Message: "缺少用户信息",
			})
			return
		}

		db := model.GetInstance().GetDB()
		var user model.Users
		if err := db.Model(&model.Users{}).Where("token = ?", token).First(&user).Error; err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				c.AbortWithStatusJSON(200, Result{
					Code:    4001,
					Data:    "",
					Message: "用户不存在",
				})
				return
			} else {
				c.AbortWithStatusJSON(200, Result{
					Code:    4001,
					Data:    "",
					Message: err.Error(),
				})
				return
			}
		}

		c.Set("user_id", user.Id)

		c.Next()
	}
}
